package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.TravelCommend;
import cn.wolfcode.trip.base.mapper.TravelCommendMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelCommendService;
import cn.wolfcode.trip.base.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class TravelCommendServiceImpl implements ITravelCommendService {

    @Autowired
    private TravelCommendMapper travelCommendMapper;


    @Override
    public PageInfo<TravelCommend> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<TravelCommend> list = travelCommendMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(TravelCommend entity) {
        if(entity.getType() == TravelCommend.TYPE_STRATEGY){
            travelCommendMapper.deleteByType(TravelCommend.TYPE_STRATEGY);
            travelCommendMapper.insert(entity);
            return;
        }
        if(entity.getId() == null){
            List<TravelCommend> commends = selectCommend(entity.getType());
            for (TravelCommend commend : commends) {
                if(commend.getTravelId()==entity.getTravelId()){
                    throw new RuntimeException("请勿重复提交");
                }
            }
            if(commends.size()<3 ) {
                travelCommendMapper.insert(entity);
            }else {
                throw new RuntimeException("推荐已满");
            }
        }else{
            travelCommendMapper.updateByPrimaryKey(entity);
        }
    }

    @Override
    public List<TravelCommend> selectCommend(Integer type) {
        Date beginDate = null;
        Date endDate = new Date();
        if(type == TravelCommend.TYPE_WEEK){
            beginDate = DateUtil.getSevenDaysAgo(endDate);
        }else if(type == TravelCommend.TYPE_MONTH){
            beginDate = DateUtil.getAMonthAgo(endDate);
        }else if(type == TravelCommend.TYPE_STRATEGY){

        }else{
            throw new RuntimeException("错误的类型");
        }
        return travelCommendMapper.selectCommend(beginDate,endDate,type);
    }
}
